using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace zevenseas.Community.Web.UI.WebControls.WebParts
{
    public class CodeplexStatistics : zsWebPart, IWebEditable
    {
        private string allReleases;

        [WebBrowsable(true), WebDisplayName("Releases")]
        [Personalizable(PersonalizationScope.Shared), SPWebCategoryName("Codeplex Statistics")]
        [DefaultValue("")]
        public string AllReleases
        {
            get { return allReleases; }
            set { allReleases = value; }
        }

        private string GetPage(string ReleaseUrl)
        {
            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                return client.DownloadString(ReleaseUrl);
            }
        }

        protected override void CreateChildControls()
        {
            string releaseTitle;
            string numberOfDownloads;
            Panel codeplexStatistics;
            HttpContext httpCtxt = HttpContext.Current;

            if (string.IsNullOrEmpty(allReleases))
            {
                Literal configWebPart = new Literal();
                configWebPart.Text = "To configure this web part, <a href=" + GetToolPaneLink() +
                                     ">open the tool pane</a> and then enter your release URL's";
                Controls.Add(configWebPart);
                return;
            }

            codeplexStatistics = (Panel)httpCtxt.Cache["codeplexStats" + this.ID];

            if (codeplexStatistics == null)
            {
                codeplexStatistics = new Panel();

                char[] splitter = {';'};
                string[] arrAllReleases = allReleases.Split(splitter, StringSplitOptions.RemoveEmptyEntries);

                DataTable dtAllReleases = new DataTable();
                dtAllReleases.Columns.Add("Release", typeof(string));
                dtAllReleases.Columns.Add("Downloads", typeof(int));

                foreach (string release in arrAllReleases)
                {
                    string releasePage = GetPage(release);
                    releaseTitle = GetTitleFromRelease(releasePage);
                    releaseTitle = release + ", " + releaseTitle;
                    numberOfDownloads = GetDownloadsFromRelease(releasePage);
                    if (!string.IsNullOrEmpty(releaseTitle) && !string.IsNullOrEmpty(numberOfDownloads)) dtAllReleases.Rows.Add(releaseTitle, int.Parse(numberOfDownloads));
                }

                SPGridView codeplexStatisticsGrid = new SPGridView();
                codeplexStatisticsGrid.AutoGenerateColumns = false;
                codeplexStatisticsGrid.DataSource = dtAllReleases;

                SPBoundUrlField bfRelLink = new SPBoundUrlField();
                bfRelLink.DataField = "Release";
                bfRelLink.HeaderText = "Release";
                codeplexStatisticsGrid.Columns.Add(bfRelLink);

                SPBoundField bfDownloads = new SPBoundField();
                bfDownloads.DataField = "Downloads";
                bfDownloads.HeaderText = "Downloads";
                codeplexStatisticsGrid.Columns.Add(bfDownloads);

                codeplexStatisticsGrid.DataBind();

                codeplexStatistics.Controls.Add(codeplexStatisticsGrid);

                httpCtxt.Cache.Insert("codeplexStats" + this.ID, codeplexStatistics, null, DateTime.Now.AddMinutes(15), System.Web.Caching.Cache.NoSlidingExpiration);
            }

            Controls.Add(codeplexStatistics);

            base.CreateChildControls();
        }

        private string GetTitleFromRelease(string releasePage)
        {
            int startIndex = releasePage.IndexOf(@"class=""CodePlexPageHeader""");
            if (startIndex == -1) return null;

            startIndex = startIndex + 27;

            int finishIndex = releasePage.IndexOf("</span>", startIndex);
            if (finishIndex == -1) return null;

            return releasePage.Substring(startIndex, finishIndex - startIndex);
        }

        private string GetDownloadsFromRelease(string releasePage)
        {
            int startIndex = releasePage.IndexOf(@"MasterContent_Content_ReleaseDownloadsLiteral");
            if (startIndex == -1) return null;
            startIndex = startIndex + 47;

            int finishIndex = releasePage.IndexOf(" ", startIndex);
            //int finishIndex = startIndex + 2;
            if (finishIndex == -1) return null;

            return releasePage.Substring(startIndex, finishIndex - startIndex);
        }

        EditorPartCollection IWebEditable.CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();

            EditorPart CodeplexStatisticsEditor = new CodeplexStatisticsEditor();
            CodeplexStatisticsEditor.ID = "CodeplexStatistics" + this.ID;

            editors.Add(CodeplexStatisticsEditor);
            return new EditorPartCollection(editors);
        }

        object IWebEditable.WebBrowsableObject
        {
            get { return this; }
        }

    }
}